package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.model.Hapi;
import com.tencent.wxcloudrun.model.ResultVo;
import com.tencent.wxcloudrun.model.Rwtf;
import com.tencent.wxcloudrun.service.RwtfService;
import com.tencent.wxcloudrun.utils.DeviceUtils;
import com.tencent.wxcloudrun.utils.ResultVoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/common/read")
public class ReadController {

    final RwtfService rwtfService;
    public ReadController(@Autowired RwtfService rwtfService) {
        this.rwtfService = rwtfService;
    }
    /**
     * 跳转到协议页面
     */
    @GetMapping("/article/{sn}")
    public String toArticle(@PathVariable String sn  , Model model) {
        // 生成唯一的会话标识
        String sessionId = DeviceUtils.getUUID();
        model.addAttribute("sessionId", sessionId);
        model.addAttribute("sn", sn);
        return "article";
    }

    @PostMapping("/article")
    @ResponseBody
    @CrossOrigin
    public ResultVo getArticle(@RequestBody Hapi hapi, HttpServletRequest request) {
        //获取会话id
        String deviceId = hapi.getSessionId();
        //获取访问次数
        int visitNum = DeviceUtils.getVisitNum(deviceId) + 1;
        if(visitNum > DeviceUtils.VISIT_LIMIT){
            DeviceUtils.deleteDeviceCache(deviceId);
            return ResultVoUtil.error("访问上限！");
        }
        //随机获取一条任务
        Rwtf rwtf = rwtfService.randRwtfCache();
        if(rwtf != null)
        {
            if(visitNum==2)
            {
                String visitAddress = DeviceUtils.getVisitAddress(deviceId);
                // 判断第二次访问是否重复， 重复需要重新获取
                if(visitAddress.equals(rwtf.getLinkAddress()))
                {
                    int cacheCount = rwtfService.getCacheCount();
                    if (cacheCount < 2){
                        return ResultVoUtil.error("无更多推广数据");
                    }
                    rwtf = rwtfService.randRwtfCacheNoRepeat(visitAddress);

                    if (rwtf == null){
                        return ResultVoUtil.error("无更多推广数据");
                    }
                    if (rwtf.getLinkAddress().equals(visitAddress)){
                        return ResultVoUtil.error("无更多推广数据");
                    }
                }
            }
            //记录访问次数
            DeviceUtils.saveDeviceCache(deviceId,visitNum,rwtf.getLinkAddress());
            return ResultVoUtil.success("",rwtf.getLinkAddress());
        }
        return ResultVoUtil.error("无推广数据！请添加");
    }

}
